/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nio_bytebuffer_bytearray;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author teva
 */
public class NIO_ByteBuffer_ByteArray {

     private static long start;
    private static long end;
    private static String Filepath;
    private static boolean Blocking = true; 

    public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException 
    {
         //String Filepath = "/Users/teva/Desktop/Results/DataFile/File1.txt";
        // NIOClient.SendFile(Filepath, 24576);
        
        int BufferSize = 4000512; 
        int k=0;
        int l=0;
        writeResult("================================");
        writeResult("NIO_ByteBuffer_ByteArray");
        writeResult("Configuration Blocking =>" + Blocking);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
        Date date = new Date();
        writeResult("Test Date  " + dateFormat.format(date));
        writeResult("Included: [Prefetching.]");
        writeResult("Buffer Size =>" + BufferSize);
        writeResult("================================");
        
        
        for(int i=11;i<12;i++) //To crawl 10 files
        {

          StringBuilder FP = new StringBuilder("/Users/teva/Desktop/DataFile/File").append(i).append(".txt"); 
                   
          Filepath = FP.toString();
          
          Prefecthing(Filepath,BufferSize);
                    
          StringBuilder FileName = new StringBuilder("File").append(i).append(".txt");
               
              for(k=1;k<2;k++) //this loop is used to change the buffer size
                 {
                    for(l=1;l<4;l++)
                     {
                        writeResult("Iteration No=> " + l + " AND File name is=> " + FileName.toString() + "Total time =>" + SendFile(Filepath, BufferSize));
                     }                
                 } 
            }  
    }
    
     public static void Prefecthing(String FilePath,int Buffer) throws FileNotFoundException, IOException 
    {
        
        FileChannel fc1 = null;
        
        fc1 = new FileInputStream(FilePath).getChannel();
        
        ByteBuffer bb = ByteBuffer.allocate(Buffer);
        
        int len=0;
        
        while((len=fc1.read(bb))>=0) 
        {
          bb.clear();
        }
       
    }
    
    static long Totaltime;
     
    public static long SendFile(String FilePath,int bufferSize)
    {
     int len;
     int tot;
     int perc = 0;
     SocketChannel sc = null;
     FileChannel fc = null; 
     File input = new File(FilePath);     
     try
      {
            System.out.println("Client NIO initiating...");            
            sc = SocketChannel.open();            
            boolean connected = sc.connect(new InetSocketAddress("10.141.11.125",3289)); 
            
            if(!connected)
            {
                connected = sc.finishConnect();
            }
            
            if(!connected)
            {
                throw(new IOException("Client failed to connect"));
            }
            
            System.out.println("Client channel connected");  
            
            sc.configureBlocking(Blocking);   
            
            
            fc = new FileInputStream(input).getChannel(); 
           
            len=0;
            
            tot=0; 
            
           
            start = System.currentTimeMillis();
            
         
            ByteBuffer buff = ByteBuffer.allocate(bufferSize);   
            
            while((len=fc.read(buff))>=0||buff.position()>0) 
            {
                buff.flip();
                sc.write(buff);
                buff.compact();
            } 
          end = System.currentTimeMillis();
          
          Totaltime = end-start;
          
          sc.close();
          fc.close();  
          return Totaltime;
      }
      catch (IOException e) 
      {
            return -1;
      }     
    }
   
     
     public static void writeResult(String Results)
     {
    try {
        FileWriter outFile = new FileWriter("/Users/teva/Desktop/FinalResult/NIO_ByteBuffer_ByteArray.txt",true);
        PrintWriter out = new PrintWriter(outFile);
        out.println(Results);        
        out.close();
} 
    catch(IOException e)
    {}
    
     }
}
